package dataBase;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class QueryDB 
{
	private static ConnectDB db = null;
	private Statement dbQuery = null;
	public QueryDB(ConnectDB db)
	{
		QueryDB.db = db;
	}
	
	public QueryDB()
	{
		if( QueryDB.db == null )
		{
			QueryDB.db = new ConnectDB();
		}
	}	
	/**
	 * Executes SELECT SQL queries
	 * @param sql - an SQL statement to be sent to the database, typically a static SQL SELECT statement.
	 * @return returns ResultSet object of the current statement
	 * @throws SQLException
	 */
	public ResultSet dbSqlQuery(String sql) throws SQLException
	{
		//@todo: restrict this to SELECT only
		//clearing old queries
		this.dbQuery = null;
		//creating new statements
		this.dbQuery = QueryDB.db.getConnection().createStatement();
		this.dbQuery.executeQuery(sql);
		
		return this.dbQuery.getResultSet();
		
	}
	

	/**
	 * Method for UPDATE, INSERT and DELETE queries
	 * @param sql - an SQL Data Manipulation Language (DML) statement, such as INSERT, UPDATE or DELETE; or an SQL statement that returns nothing, such as a DDL statement. 
	 * @throws SQLException
	 */
	public void dbSqlUpdate(String sql) throws SQLException
	{
		//clearing old queries
		this.dbQuery = null;
		//creating new statements
		this.dbQuery = QueryDB.db.getConnection().createStatement();
		this.dbQuery.executeUpdate(sql);
		this.dbQuery.getResultSet();
	}
	
	/**
	 * Commits last update operations
	 * @throws SQLException
	 */
	public void dbCommit() throws SQLException
	{
		QueryDB.db.getConnection().commit();
	}
	
	/**
	 * Rollbacks last ubdate operations;
	 * @throws SQLException
	 */
	public void dbRollback() throws SQLException
	{
		QueryDB.db.getConnection().rollback();
	}

}
